package main

import (
	"fmt"
	"github.com/op/go-logging"
	"gopkg.in/yaml.v2"
	"io/ioutil"
)

type Config struct {
	Sender         map[string]string   `yaml:"sender"`
	Repeaters      []map[string]string `yaml:"repeaters"`
	RestAddress    string              `yaml:"rest_address"`
	CommitPath     string              `yaml:"commit_path"`
	CommitInterval int                 `yaml:"commit_interval"`
	LogLevelStr    string              `yaml:"log_level"`
	logLevel       logging.Level
}

func LoadConfig(filename string) (*Config, error) {
	content, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	cfg := &Config{}
	if err := yaml.Unmarshal(content, cfg); err != nil {
		return nil, err
	}
	LEVELS := map[string]logging.Level{
		"critical": logging.CRITICAL,
		"error":    logging.ERROR,
		"warning":  logging.WARNING,
		"notice":   logging.NOTICE,
		"info":     logging.INFO,
		"debug":    logging.DEBUG,
	}
	level, ok := LEVELS[cfg.LogLevelStr]
	if !ok {
		level = logging.INFO
	}
	cfg.logLevel = level
	if cfg.CommitPath == "" || cfg.CommitInterval == 0 || len(cfg.Sender) == 0 || len(cfg.Repeaters) == 0 {
		return nil, fmt.Errorf("error in config: %v", *cfg)
	}
	if _, ok := cfg.Sender["type"]; !ok {
		return nil, fmt.Errorf("No Type defined")
	}
	for _, item := range cfg.Repeaters {
		if _, ok := item["type"]; !ok {
			return nil, fmt.Errorf("No Type defined")
		}
	}
	return cfg, nil
}
